﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DB_test.Models
{
    static class DiverMap
    {
        public static List<Diver> ReadDiversFromDatabase()
        {
            var divers = new List<Diver>();
            foreach (var data in MyDbConnection.ReadFromDataBase("select * from divers order by id"))
                divers.Add(Diver.GetFromDictionary(data));
            return divers;
        }

        public static void SaveDiversToDatabase(List<Diver> divers)
        {
            foreach (var diver in divers)
                SaveDiverToDatabase(diver);
        }

        public static void RemoveDiver(Diver diver)
        {
            foreach (var jump in diver.Jumps)
                JumpMap.RemoveJump(jump);
            var removeString = String.Format("delete from divers where {0}='{1}'", Diver.GetIdField(), diver.Id);
            MyDbConnection.ExecuteUpdate(removeString);
        }

        public static void SaveDiverToDatabase(Diver diver)
        {
            var existingDiver = MyDbConnection.ReadFromDataBase(String.Format("select * from divers where {0}={1}", Diver.GetIdField(), diver.Id));
            var data = diver.GetDictionary();
            if (existingDiver.Count == 0) // New Diver;
            {
                var insertString = String.Format("insert into divers {0}", GenerateSqlQuerys.InsertQuery(data, Diver.GetIdField()));
                diver.Id = MyDbConnection.ExecuteInsert(insertString);
            }
            else // Existing Diver
            {
                var updateString = String.Format("update divers set {0}", GenerateSqlQuerys.UpdateQuery(data, Diver.GetIdField()));
                MyDbConnection.ExecuteUpdate(updateString);
            }
            foreach (var jump in diver.Jumps)
                JumpMap.SaveJumpToDatabase(jump);
        }


    }
}
